package com.agile.leetcode.queue.delayedqueue;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 实现延时队列存放元素的接口
 *
 * @Author:ChenZhangKun
 * @Date: 2021/9/28 14:04
 */
public class Item implements Delayed {
    private String name;
    private Long time;

    public Item(String name, Long time, TimeUnit unit) {
        this.name = name;
        this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0);
    }

    /**
     * 剩余的过期时间
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        // 剩余过期时间
        return this.time - System.currentTimeMillis();
    }

    /**
     * 定义排序规则
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        // 强转
        Item item = (Item) o;
        long diff = this.time - item.time;
        if (diff <= 0) {
            return -1;
        } else {
            return 1;
        }
    }

    @Override
    public String toString() {
        return "Item{" +
                "name='" + name + '\'' +
                ", time=" + time +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }
}
